package org.zjx.window.strategy;


import org.zjx.window.window.IWindow;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 策略工厂
 */
public class StrategyFactory {
    private static StrategyFactory instance;
    private final Map<String, IStrategy> strategyMap = new HashMap<>();

    public StrategyFactory() {
        // 使用 SPI 动态注册策略
        loadStrategies();
        System.out.println("[策略工厂] 初始化完成，已注册策略数量: " + strategyMap.size());
    }

    public static synchronized StrategyFactory getInstance() {
        if (instance == null) {
            instance = new StrategyFactory();
        }
        return instance;
    }

    /**
     * 使用 SPI 机制动态加载并注册所有策略
     */
    private void loadStrategies() {
        ServiceLoader<IStrategy> loader = ServiceLoader.load(IStrategy.class,
                Thread.currentThread().getContextClassLoader());

        for (IStrategy strategy : loader) {
            registerStrategy(strategy);
        }

        // 如果没有找到任何策略，则注册默认策略
        if (strategyMap.isEmpty()) {
            throw new IllegalArgumentException("策略为空！！！");
        }
    }

    /**
     * 注册策略
     */
    public void registerStrategy(IStrategy strategy) {
        strategyMap.put(strategy.getName(), strategy);
        System.out.println("[策略工厂] 注册策略: " + strategy.getName());
    }

    /**
     * 选择合适的策略并生成指令
     */
    public IStrategy selectAndExecuteStrategy(IWindow window) {

        // 获取所有策略并按优先级排序
        List<IStrategy> sortedStrategies = getAllStrategies();

        // 先进行快速预筛选
        List<IStrategy> candidateStrategies = sortedStrategies.stream()
                .filter(strategy -> strategy.isApplicable(window))
                .collect(Collectors.toList());

        // 然后按优先级深度检查
        for (IStrategy strategy : candidateStrategies) {
            System.out.println("[策略工厂] 选择策略: " + strategy.getName());
            return strategy;
        }

        // 默认策略
        System.out.println("[策略工厂] 使用默认策略");
        return getDefaultStrategy();
    }

    /**
     * 获取特定策略
     */
    public IStrategy getStrategy(String name) {
        return strategyMap.get(name);
    }

    /**
     * 获取默认策略
     */
    public IStrategy getDefaultStrategy() {
        return strategyMap.get("DefaultStrategy");
    }

    /**
     * 获取所有策略（按优先级排序）
     */
    public List<IStrategy> getAllStrategies() {
        return strategyMap.values().stream()
                .sorted(Comparator.comparingInt(IStrategy::getPriority))
                .collect(Collectors.toList());
    }

    /**
     * 清空所有策略
     */
    public void clearStrategies() {
        strategyMap.clear();
        System.out.println("[策略工厂] 已清空所有策略");
    }

    /**
     * 获取策略数量
     */
    public int getStrategyCount() {
        return strategyMap.size();
    }
}